package com.nowcoder.community.community.controller;

import com.nowcoder.community.community.annotation.LoginRequire;
import com.nowcoder.community.community.entity.User;
import com.nowcoder.community.community.service.UserService;
import com.nowcoder.community.community.util.CommunityUtil;
import com.nowcoder.community.community.util.HostHolder;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Value("${community.path.upload}")
    private String uploadPath;

    @Value("${community.path.domain}")
    private String domain;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Autowired
    private UserService userService;

    @Autowired
    private HostHolder hostHolder;//获取当前用户

//    转到设置页面
    @LoginRequire
    @RequestMapping(path = "/setting",method = RequestMethod.GET)
    public String getSettingPage(){
        return "/site/setting";
    }

//    设置头像
    @LoginRequire
    @RequestMapping(path = "/upload",method = RequestMethod.POST)
    public String uploadHeader(MultipartFile headerImage, ModelMap model){
        if(headerImage == null || headerImage.isEmpty()){
            model.addAttribute("error","还没有上传图片！");
            return "/site/setting";
        }

        String originalFilename = headerImage.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.indexOf("."));
        if(StringUtils.isBlank(suffix)){
            model.addAttribute("error","文件格式不正确！");
            return "/site/setting";
        }
        //生成随机文件名
        originalFilename = CommunityUtil.generateUUID() + suffix;
        //确定文件存放路径
        File dest = new File(uploadPath + "/" + originalFilename);

        try {
            headerImage.transferTo(dest);
        } catch (IOException e) {
            logger.error("上传文件失败："+e.getMessage());
            throw new RuntimeException("上传文件失败，服务器异常！",e);
        }

        //更新当前用户的头像的路径（web访问路径）
        //http://localhost:8080/community/user/header/xxx.png
        User user = hostHolder.getUser();
        String headerUrl = domain + contextPath + "/user/header/" + originalFilename;
        userService.updateHeader(user.getId(),headerUrl);

        return "redirect:/index";
    }

    @RequestMapping(path = "/header/{originalFilename}",method = RequestMethod.GET)
    public void getHeader(@PathVariable("originalFilename") String originalFilename, HttpServletResponse response){
        //头像在服务器存放路径
        originalFilename = uploadPath + "/" + originalFilename;
        //文件后缀
        String suffix = originalFilename.substring(originalFilename.indexOf("."));
        //响应图片
        response.setContentType("image/" + suffix);
        try(
                FileInputStream fileInputStream = new FileInputStream(originalFilename);
                OutputStream os =  response.getOutputStream();) {
            byte[] buffer = new byte[1024];
            int b = 0;
            while ((b = fileInputStream.read(buffer)) != -1){
                os.write(buffer,0,b);
            }
        } catch (IOException e) {
            logger.error("读取头像失败！" + e.getMessage());
        }
    }

//    更新密码
    @LoginRequire       //该注释表示需要登陆后才能访问该方法
    @RequestMapping(path = "/setting",method = RequestMethod.POST)
    public String update(ModelMap model, String newPassword, String oldPassword, String newName){
        User user = hostHolder.getUser();
        Map<String, Object> map = userService.updatePassword(user.getId(), oldPassword, newPassword);
        //修改用户名
        Map<String, Object> usernameMap = new HashMap<>();
        if(!newName.equals(user.getUsername())){
            usernameMap = userService.upadeUserName(user.getId(),newName);
        }
        if(map == null && usernameMap == null || map.isEmpty() && usernameMap.isEmpty()){
            return "redirect:/index";
        }else {
            model.addAttribute("oldPasswordMsg",map.get("oldPasswordMsg"));
            model.addAttribute("newPasswordMsg",map.get("newPasswordMsg"));
            model.addAttribute("usernameMsg",usernameMap.get("usernameMsg"));

            return "/site/setting";
        }
    }
}
